//app.js
const config = require('./config');
const http = require('./utils/http.js')
var app = null
App({
  globalData: {
    limit: 8,
    imgHead: 'http://p94f3cj0e.bkt.clouddn.com/',
  },
  /**
   * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
   */
  onLaunch: function () {
    var that = this
    wx.setTabBarBadge({
      index: 2,
      text: '1'
    })
  },
  // 登录
  wxLogin: function (callback) {
    var that = this
    callback = callback || function () { }
    wx.login({
      success: function (data) {
        console.log(data)
        wx.getStorageSync("wxUserInfo")
        var parentId = wx.getStorageSync("parentId") || 1
        wx.request({
          // url: config.testLoginUrl,
          url: config.openIdUrl,
          data: {
            code: data.code,
            encryptedData: wx.getStorageSync("encryptedData"),
            iv: wx.getStorageSync("iv"),
            parentId: parentId
          },
          success: function (res) {   
            console.log(res)       
            wx.setStorageSync("X-Nideshop-Token", res.data.data)
            callback()
          },
          fail: function (res) {
            
          },
          complete: function (res) {
          }
        })
      },
      fail: function (err) {
        
      },
      complete: function (res) {

      }
    })
  },

  /**
   * 多张图片，只保留第一张图片，并添加头地址
   */
  cutImg: function(list) {
    var that = this
    list.forEach(function (el) {
      var pic = el.imgs.split(",")
      el.imgs = that.globalData.imgHead + pic[0]
    })
    return list
  },
  /**
   * 多张图片，只保留第一张，不生成列表
   */
  picCut: function(imgs) {
    var that = this
    var pic = imgs.split(",")
    return that.globalData.imgHead + pic[0]
  },
  /**
   * 将多张图片转换成数组，并添加头地址
   */
  imgArr: function(imgs) {
    var that = this
    var pic = imgs.split(",")
    var imgsArr = []
    pic.forEach(function(el){
      imgsArr.push(that.globalData.imgHead + el)
    })
    return imgsArr
  },
  /**
   * 将单张图片添加头地址
   */
  handleImg: function(img) {
    var that = this
    if(img.length == 0) {
      return ''
    }
    return that.globalData.imgHead + img
  },
  /**
   * 列表图片添加图片头地址
   */
  arrImg: function(arr) {
    var that = this
    arr.forEach(function(el){
      el.avatar = that.globalData.imgHead + el.avatar
    })
    return arr
  },
})

// TEXT(0,"文本消息"),IMAGE(2,"图片"),MEDIA(3,"视屏"),CONNECT(4, "第一次(或重连)初始化连接"),KEEPALIVE(5, "客户端保持心跳"),FRIEND(6, "拉取好友");